"""
认证相关服务
"""
from datetime import datetime
from flask_jwt_extended import create_access_token
from app.models.user import User
from app.extensions import db
from app.utils.errors import AuthError, ValidationError

class AuthService:
    """认证服务类"""
    
    @staticmethod
    def login(username, password):
        """用户登录"""
        if not username or not password:
            raise ValidationError("用户名和密码不能为空")
        
        user = User.query.filter_by(username=username).first()
        
        if not user or not user.check_password(password):
            raise AuthError("用户名或密码错误")
        
        if not user.is_active:
            raise AuthError("账户已禁用")
        
        # 更新最后登录时间
        user.last_login = datetime.now()
        db.session.commit()
        
        # 创建访问令牌
        access_token = create_access_token(identity=user.id)
        
        return {
            "access_token": access_token,
            "user": user
        }
    
    @staticmethod
    def change_password(user_id, old_password, new_password):
        """修改密码"""
        user = User.query.get(user_id)
        
        if not user:
            raise ValidationError("用户不存在")
        
        if not old_password or not new_password:
            raise ValidationError("旧密码和新密码不能为空")
        
        if not user.check_password(old_password):
            raise AuthError("旧密码不正确")
        
        # 设置新密码
        user.set_password(new_password)
        db.session.commit()
        
        return {
            "msg": "密码修改成功"
        } 